package com.coollang.smartbra.presenter;

import android.os.Handler;
import android.os.Message;

import com.coollang.smartbra.activity.NewActionActivity;
import com.coollang.smartbra.beans.NewActionData;
import com.coollang.smartbra.fragment.NewActionCountFragment;
import com.coollang.smartbra.fragment.NewActionTimeFragment;
import com.coollang.smartbra.utils.ActionTypeParse;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.ArrayList;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: Timmy
 * @data: 2017/12/18
 * @Fuction:
 */
public class NewActionTimeFragmentPresenter {

    private ScheduledThreadPoolExecutor mExecutorService;
    private NewActionTimeFragment mFragment;
    private int mProgress;

    private static final int HANDLER_WHAT1 = 10;
    private static final int HANDLER_WHAT2 = 20;

    private int currentFlag = 0;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            if (msg.what == HANDLER_WHAT2) {
                if (mFragment != null) {
                    mFragment.setTvSecond(mMassageTime, mCorentMassageTime);
                }
            }
            super.handleMessage(msg);
        }
    };

    private static final int CORRECT_FLAG = 1;
    private static final int ERROR_FLAG = 2;
    private long mStartTime;
    private ScheduledFuture<?> mScheduledFuture;
    private ArrayList<NewActionData> mActionDatas = new ArrayList<>();

    public NewActionTimeFragmentPresenter(NewActionTimeFragment fragment) {
        mFragment = fragment;
        // ScheduledExecutorService 替换 Timer
        mExecutorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory
                .Builder().daemon(true).build());
    }

    public void onDestroyView() {
        shutDown();
        mExecutorService.shutdown();
        mStartTime = 0;
        mHandler.removeCallbacks(mRunnable);
    }

    public void startCount() {
        mHandler.post(mRunnable);
        mHandler.sendEmptyMessage(HANDLER_WHAT1);
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (mProgress < NewActionCountFragment.PROGRESSBAR_MAX) {
                // 小于1000
                mProgress += 15;
                mFragment.setCircularSeekBarProgress(mProgress);
                mHandler.postDelayed(this, 1);
            }
        }
    };

    public int getProgress() {
        return mProgress;
    }

    public void setProgress(int progress) {
        mProgress = progress;
    }

    public void setMassageTime(long massageTime) {
        mMassageTime = massageTime;
    }

    public void removeHandler() {
        mHandler.removeCallbacks(mRunnable);
    }

    public void startCounting() {
        if (mStartTime == 0) {
            mStartTime = System.currentTimeMillis() / 1000;
        }
        mScheduledFuture = mExecutorService.scheduleWithFixedDelay(new TimerTask(), 0, UPDATE_TIME, TimeUnit.MILLISECONDS);
    }

    private static int UPDATE_TIME = 34;

    private class TimerTask implements Runnable {
        @Override
        public void run() {
            try {
                mMassageTime += UPDATE_TIME;
                if (currentFlag == 1) {
                    mCorentMassageTime += UPDATE_TIME;
                }

                mHandler.sendEmptyMessage(HANDLER_WHAT2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void shutDown() {
        if (mScheduledFuture != null) {
            mScheduledFuture.cancel(true);
        }

        //  mMassageTime = 0;
    }

    /**
     * 运动时间
     */
    private long mMassageTime = 0;
    /**
     * 正确的运动时间
     */
    private long mCorentMassageTime = 0;

    /**
     * @param heartRate  心率
     * @param actionFlag 是否是正确或者错误动作
     * @param errorType  错误动作详情
     */
    public void processCountData(int heartRate, int actionFlag, int errorType) {
        currentFlag = actionFlag;

        int actionType = mFragment.getActionType();
        if (mActionDatas.size() > 0) {
            // 判断上一个
            NewActionData actionData = mActionDatas.get(0);
            int lastActionFlag = actionData.getActionFlag();
            if (actionFlag == CORRECT_FLAG) {
                if (lastActionFlag != actionFlag) {
                    addData(actionType, heartRate, actionFlag, errorType);
                }
            } else if (actionFlag == ERROR_FLAG) {
                int lastErrorType = actionData.getErrorType();
                if (lastActionFlag != actionFlag) {
                    addData(actionType, heartRate, actionFlag, errorType);
                } else {
                    if (lastErrorType != errorType) {
                        addData(actionType, heartRate, actionFlag, errorType);
                    }
                }
            }
        } else {
            addData(actionType, heartRate, actionFlag, errorType);
        }

        // 播报语音项目
        if (actionFlag == CORRECT_FLAG) {
            actionType = -1;
        }
        int actionVoice = ActionTypeParse.getActionVoice(actionType, errorType);
        ((NewActionActivity) mFragment.getContext()).playVoice(actionVoice);
    }

    private void addData(int actionType, int heartRate, int actionFlag, int errorType) {
        NewActionData actionData = new NewActionData();
        actionData.setActionType(actionType);
        actionData.setStartTime(System.currentTimeMillis());
        actionData.setHeartRate(heartRate);
        actionData.setActionFlag(actionFlag);
        actionData.setErrorType(errorType);
        actionData.setTime(0);
        mActionDatas.add(0, actionData);

        // mFragment.getFragmentAdapter().setNewData(mActionDatas);
        mFragment.getFragmentAdapter().addData(0, actionData);
        // mFragment.getFragmentAdapter().notifyDataSetChanged();
        mFragment.getRecyclerView().scrollToPosition(0);


    }

    public ArrayList<NewActionData> getActionDatas() {
        return mActionDatas;
    }

    public long getCorrentMessageTime() {
        return mCorentMassageTime;
    }

    public long getStartTime() {
        return mStartTime;
    }


}
